package com.woniuxy.ticket.ticketfile.controller;

import com.woniuxy.ticket.commons.entity.ResponseResult;
import com.woniuxy.ticket.ticketfile.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${file.location}")
    private String fileLocation;

    @Autowired
    private OssUtil ossUtil;

    @PostMapping("/upload")
    public ResponseResult upload(MultipartFile file){
        //随机生成文件名
        String fileName = UUID.randomUUID().toString().replaceAll("-","");
        //截取后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        File file1 = new File(fileLocation);
        if(!file1.exists()){
            file1.mkdirs();
        }
        File newFile = new File(file1,fileName+suffix);
        try {
            file.transferTo(newFile);
        }catch (IOException e){
            e.printStackTrace();
        }
        return new ResponseResult().success(fileName+suffix);
    }


    @PostMapping("/upload2oss")
    public ResponseResult upload2oss(MultipartFile file){
        String url = ossUtil.uploadFile(file); //2、调用

        return new ResponseResult().success(url);
    }


}
